<?php

class Core_Validator {

    public function __construct() {

    }

    public function validateReferer($refer) {
        if ($refer == null) {
            die("不要从外部提交!");
        }
        return true;
    }

    /**
     * 同样的IP不能在1天能多投票5次...
     */
    public function validateIpAddress($ip) {        
        $current_date = date('Y-m-d');
        $db = Core_Db::factory();
        $sql = "select count(*) as count from vote where date(regist_dt) = ?";
        $sql = $db->quoteInto($sql, $current_date);
        $sql = $sql . ' and from_ip = ?';
        $sql = $db->quoteInto($sql, $ip);
        $ret = $db->fetchRow($sql);
        if ($ret['count'] > 2)
        {
            return false;
        }
        return true;
    }

    /**
     * 人数不能超过20
     */
    public function validatePersonCount($person_ids) {
        $arr = explode(",", $person_ids);
        if (count($arr) > 20) {
            return false;
        }
        return true;
    }

    /**
     *
     * 随机问题生成
     *
     */
    public function randomBrainFuck() {

        $session = new Zend_Session_Namespace("random.ques");
        if (!is_null($session->question)) return $session->question;

        $xml = file_get_contents("BrainFuck/rq.xml");
        $p = xml_parser_create();
        xml_parse_into_struct($p, $xml, $vals);
        xml_parser_free($p);
        $count = 0;
        $q = array();
        foreach($vals as $tag)
        {
            if ($tag['tag'] == 'Q')
            {
                $q[] = $tag;
            }
        }
        $rand = rand(0 , count($q)-1);
        
        $session->answer = $q[$rand]['attributes']['A'];;
	$q[$rand]['right_answer'] = $q[$rand]['attributes']['A'];
        $session->question = $q[$rand];

        return $q[$rand];
    }

    /**
     *
     * 随机问题答案是否正确
     *
     */
    public function validateBrainFuckAnswer($answer) {
        $session = new Zend_Session_Namespace("random.ques");
        if ($session->answer == $answer)
        {
            Zend_Session::namespaceUnset('random.ques');
            return true;
        }
        return false;
    }

}
